<?php
use Think\Model;
/**
 * tpshop检验登陆
 * @param
 * @return bool
 */
function is_login(){
    if(isset($_SESSION['admin_id']) && $_SESSION['admin_id'] > 0){
        return $_SESSION['admin_id'];
    }else{
        return false;
    }
}
/**
 * 获取用户信息
 * @param $user_id_or_name  用户id 邮箱 手机 第三方id
 * @param int $type  类型 0 user_id查找 1 邮箱查找 2 手机查找 3 第三方唯一标识查找
 * @param string $oauth  第三方来源
 * @return mixed
 */
function get_user_info($user_id_or_name,$type = 0,$oauth=''){
    $map = array();
    if($type == 0)
        $map['user_id'] = $user_id_or_name;
    if($type == 1)
        $map['email'] = $user_id_or_name;
    if($type == 2)
        $map['mobile'] = $user_id_or_name;
    if($type == 3){
        $map['openid'] = $user_id_or_name;
        //$map['oauth'] = $oauth;
    }
    if($type == 4){
    	$map['unionid'] = $user_id_or_name;
    	//$map['oauth'] = $oauth;
    }
	
    $user = M('users')->where($map)->find(); 
    return $user;
}

/**
 * 更新会员等级,折扣，消费总额
 * @param $user_id  用户ID
 * @return boolean
 */
function update_user_level($user_id){
    $level_info = M('user_level')->order('level_id')->select();
    //下单金额
    $total_amount = M('order')->where("user_id=$user_id AND order_status not in (3,5)")->sum('order_amount');
    //退货金额
    $return_amount = M('return_goods')->where(['user_id'=>$user_id,'withdrawals_id'=>['gt',0]])->sum('(member_goods_price+yijia)*goods_num');
    $total_amount = $total_amount-$return_amount;
    if($level_info){
    	foreach($level_info as $k=>$v){
    		if($total_amount >= $v['amount']){
    			$level = $level_info[$k]['level_id'];
    			$discount = $level_info[$k]['discount']/100;
    		}
    	}
    	$user = session('user');
    	$updata['total_amount'] = $total_amount;//更新累计修复额度
    	//累计额度达到新等级，更新会员折扣
    	if(isset($level) && $level>$user['level']){
    		$updata['level'] = $level;
    		$updata['discount'] = $discount;
    	}
    	M('users')->where("user_id=$user_id")->save($updata);
    }
}

/**
 *  商品缩略图 给于标签调用 拿出商品表的 original_img 原始图来裁切出来的
 * @param type $goods_id  商品id
 * @param type $width     生成缩略图的宽度
 * @param type $height    生成缩略图的高度
 */
function goods_thum_images($goods_id,$width,$height){

     if(empty($goods_id))
		 return '';
    //判断缩略图是否存在
    $path = "Public/upload/goods/thumb/$goods_id/";
    $goods_thumb_name ="goods_thumb_{$goods_id}_{$width}_{$height}";
  
    // 这个商品 已经生成过这个比例的图片就直接返回了
    if(file_exists($path.$goods_thumb_name.'.jpg'))  return '/'.$path.$goods_thumb_name.'.jpg'; 
    if(file_exists($path.$goods_thumb_name.'.jpeg')) return '/'.$path.$goods_thumb_name.'.jpeg'; 
    if(file_exists($path.$goods_thumb_name.'.gif'))  return '/'.$path.$goods_thumb_name.'.gif'; 
    if(file_exists($path.$goods_thumb_name.'.png'))  return '/'.$path.$goods_thumb_name.'.png'; 
        
    $original_img = M('Goods')->where("goods_id = $goods_id")->getField('original_img');
    if(empty($original_img)) return '';
    
    $original_img = '.'.$original_img; // 相对路径
    if(!file_exists($original_img)) return '';

    $image = new \Think\Image();
    $image->open($original_img);
        
    $goods_thumb_name = $goods_thumb_name. '.'.$image->type();
    // 生成缩略图
    if(!is_dir($path)) 
        mkdir($path,0777,true);
    
    // 参考文章 http://www.mb5u.com/biancheng/php/php_84533.html  改动参考 http://www.thinkphp.cn/topic/13542.html
    $image->thumb($width, $height,2)->save($path.$goods_thumb_name,NULL,100); //按照原图的比例生成一个最大为$width*$height的缩略图并保存
    

    //图片水印处理
    $water = tpCache('water');
    if($water['is_mark']==1){
    	$imgresource = './'.$path.$goods_thumb_name;
    	if($width>$water['mark_width'] && $height>$water['mark_height']){
    		if($water['mark_type'] == 'img'){
    			$image->open($imgresource)->water(".".$water['mark_img'],$water['sel'],$water['mark_degree'])->save($imgresource);
    		}else{
    			//检查字体文件是否存在
    			if(file_exists('./zhjt.ttf')){
    				$image->open($imgresource)->text($water['mark_txt'],'./zhjt.ttf',20,'#000000',$water['sel'])->save($imgresource);
    			}
    		}
    	}
    }
    return '/'.$path.$goods_thumb_name;
}

/**
 * 商品相册缩略图
 */
function get_sub_images($sub_img,$goods_id,$width,$height){
	//判断缩略图是否存在
	$path = "Public/upload/goods/thumb/$goods_id/";
	$goods_thumb_name ="goods_sub_thumb_{$sub_img['img_id']}_{$width}_{$height}";
	//这个缩略图 已经生成过这个比例的图片就直接返回了
	if(file_exists($path.$goods_thumb_name.'.jpg'))  return '/'.$path.$goods_thumb_name.'.jpg';
	if(file_exists($path.$goods_thumb_name.'.jpeg')) return '/'.$path.$goods_thumb_name.'.jpeg';
	if(file_exists($path.$goods_thumb_name.'.gif'))  return '/'.$path.$goods_thumb_name.'.gif';
	if(file_exists($path.$goods_thumb_name.'.png'))  return '/'.$path.$goods_thumb_name.'.png';
	
	$original_img = '.'.$sub_img['image_url']; //相对路径
	if(!file_exists($original_img)) return '';
	
	$image = new \Think\Image();
	$image->open($original_img);
	
	$goods_thumb_name = $goods_thumb_name. '.'.$image->type();
	// 生成缩略图
	if(!is_dir($path))
		mkdir($path,777,true);
	$image->thumb($width, $height,2)->save($path.$goods_thumb_name,NULL,100); //按照原图的比例生成一个最大为$width*$height的缩略图并保存
	return '/'.$path.$goods_thumb_name;
}

/**
 * 刷新商品库存, 如果商品有设置规格库存, 则商品总库存 等于 所有规格库存相加
 * @param type $goods_id  商品id
 */
function refresh_stock($goods_id){
    $count = M("SpecGoodsPrice")->where("goods_id = $goods_id")->count();
    if($count == 0) return false; // 没有使用规格方式 没必要更改总库存

    $store_count = M("SpecGoodsPrice")->where("goods_id = $goods_id")->sum('store_count');
    M("Goods")->where("goods_id = $goods_id")->save(array('store_count'=>$store_count)); // 更新商品的总库存
}

/**
 * 根据 order_goods 表扣除商品库存
 * @param type $order_id  订单id
 */
function minus_stock($order_id){
    $orderGoodsArr = M('OrderGoods')->where("order_id = $order_id")->select();
    foreach($orderGoodsArr as $key => $val)
    {
        // 有选择规格的商品
        if(!empty($val['spec_key']))
        {   // 先到规格表里面扣除数量 再重新刷新一个 这件商品的总数量
            M('SpecGoodsPrice')->where("goods_id = {$val['goods_id']} and `key` = '{$val['spec_key']}'")->setDec('store_count',$val['goods_num']);
            refresh_stock($val['goods_id']);
        }else{
            M('Goods')->where("goods_id = {$val['goods_id']}")->setDec('store_count',$val['goods_num']); // 直接扣除商品总数量
        }
        M('Goods')->where("goods_id = {$val['goods_id']}")->setInc('sales_sum',$val['goods_num']); // 增加商品销售量
        //更新活动商品购买量
        if($val['prom_type']==1 || $val['prom_type']==2){
        	$prom = get_goods_promotion($val['goods_id']);
        	if($prom['is_end']==0){
        		$tb = $val['prom_type']==1 ? 'flash_sale' : 'group_buy';
        		M($tb)->where("id=".$val['prom_id'])->setInc('buy_num',$val['goods_num']);
        		M($tb)->where("id=".$val['prom_id'])->setInc('order_num');
        	}
        }
    }
}

/**
 * 邮件发送
 * @param $to    接收人
 * @param string $subject   邮件标题
 * @param string $content   邮件内容(html模板渲染后的内容)
 * @throws Exception
 * @throws phpmailerException
 */
function send_email($to,$subject='',$content=''){
    require_once THINK_PATH."Library/Vendor/phpmailer/PHPMailerAutoload.php";
    $mail = new PHPMailer;
    $config = tpCache('smtp');
	$mail->CharSet    = 'UTF-8'; //设定邮件编码，默认ISO-8859-1，如果发中文此项必须设置，否则乱码	
    $mail->isSMTP();
    //Enable SMTP debugging
    // 0 = off (for production use)
    // 1 = client messages
    // 2 = client and server messages
    $mail->SMTPDebug = 0;
    //调试输出格式
	//$mail->Debugoutput = 'html';
    //smtp服务器
    $mail->Host = $config['smtp_server'];
    //端口 - likely to be 25, 465 or 587
    $mail->Port = $config['smtp_port'];
	if($mail->Port === 465) $mail->SMTPSecure = 'ssl';// 使用安全协议	
    //Whether to use SMTP authentication
    $mail->SMTPAuth = true;
    //用户名
    $mail->Username = $config['smtp_user'];
    //密码
    $mail->Password = $config['smtp_pwd'];
    //Set who the message is to be sent from
    $mail->setFrom($config['smtp_user']);
    //回复地址
    //$mail->addReplyTo('replyto@example.com', 'First Last');
    //接收邮件方
    if(is_array($to)){
    	foreach ($to as $v){
    		$mail->addAddress($v);
    	}
    }else{
    	$mail->addAddress($to);
    }
    //标题
    $mail->Subject = $subject;
    //HTML内容转换
    $mail->msgHTML($content);
    //Replace the plain text body with one created manually
    //$mail->AltBody = 'This is a plain-text message body';
    //添加附件
    //$mail->addAttachment('images/phpmailer_mini.png');
    //send the message, check for errors
    if (!$mail->send()) {
        return false;
    } else {
        return true;
    }

}

/**
 * 发送短信
 * @param $mobile  手机号码
 * @param $content  内容
 * @return bool

function sendSMS($mobile,$content)
{
    $config = F('sms','',TEMP_PATH);
    $http = $config['sms_url'];			//短信接口
    $uid = $config['sms_user'];			//用户账号
    $pwd = $config['sms_pwd'];			//密码
    $mobileids = $mobile;         		//号码发送状态接收唯一编号
    $data = array
    (
        'uid'=>$uid,					//用户账号
        'pwd'=>md5($pwd.$uid),			//MD5位32密码,密码和用户名拼接字符
        'mobile'=>$mobile,				//号码，以英文逗号隔开
        'content'=>$content,			//内容
        'mobileids'=>$mobileids,
    );
    //即时发送
    $res = httpRequest($http,'POST',$data);//POST方式提交
    $stat = strpos($res,'stat=100');
    if($stat){
        return true;
    }else{
        return false;
    }
}
 */
//    /**
//     * 发送短信
//     * @param $mobile  手机号码
//     * @param $code    验证码
//     * @return bool    短信发送成功返回true失败返回false
//     */
function sendSMS($mobile, $code)
{
    //时区设置：亚洲/上海
    date_default_timezone_set('Asia/Shanghai');
    //这个是你下面实例化的类
    vendor('Alidayu.TopClient');
    //这个是topClient 里面需要实例化一个类所以我们也要加载 不然会报错
    vendor('Alidayu.ResultSet');
    //这个是成功后返回的信息文件
    vendor('Alidayu.RequestCheckUtil');
    //这个是错误信息返回的一个php文件
    vendor('Alidayu.TopLogger');
    //这个也是你下面示例的类
    vendor('Alidayu.AlibabaAliqinFcSmsNumSendRequest');

    $c = new \TopClient;
    $config = F('sms','',TEMP_PATH);
	
    //短信内容：公司名/名牌名/产品名
    $product = $config['sms_product'];
    //App Key的值 这个在开发者控制台的应用管理点击你添加过的应用就有了
    $c->appkey = $config['sms_appkey'];
    //App Secret的值也是在哪里一起的 你点击查看就有了
    $c->secretKey = $config['sms_secretKey'];
    //这个是用户名记录那个用户操作
    $req = new \AlibabaAliqinFcSmsNumSendRequest;
    //代理人编号 可选
    $req->setExtend("123456");
    //短信类型 此处默认 不用修改
    $req->setSmsType("normal");
    //短信签名 必须
    $req->setSmsFreeSignName("维亚轩");
    //短信模板 必须
    $req->setSmsParam("{\"code\":\"$code\"}");
    //短信接收号码 支持单个或多个手机号码，传入号码为11位手机号码，不能加0或+86。群发短信需传入多个号码，以英文逗号分隔，
    $req->setRecNum("$mobile");
    //短信模板ID，传入的模板必须是在阿里大鱼“管理中心-短信模板管理”中的可用模板。
    $req->setSmsTemplateCode($config['sms_templateCode']); // templateCode
    
    $c->format='json'; 
    //发送短信
    $resp = $c->execute($req);
    //短信发送成功返回True，失败返回false
    //if (!$resp) 
    if ($resp && $resp->result)   // if($resp->result->success == true)
    {
        // 从数据库中查询是否有验证码
        $data = M('sms_log')->where("code = '$code' and add_time > ".(time() - 60*60))->find();
        // 没有就插入验证码,供验证用
        empty($data) && M('sms_log')->add(array('mobile' => $mobile, 'code' => $code, 'add_time' => time(), 'session_id' => SESSION_ID));
        return true;        
    }
    else 
    {
        return false;
    }
}

/**
 * 查询快递
 * @param $postcom  快递公司编码
 * @param $getNu  快递单号
 * @return array  物流跟踪信息数组
 */
function queryExpress($postcom , $getNu){
    $url = "http://wap.kuaidi100.com/wap_result.jsp?rand=".time()."&id={$postcom}&fromWeb=null&postid={$getNu}";
    //$resp = httpRequest($url,'GET');
    $resp = file_get_contents($url);
    if (empty($resp)) {
        return array('status'=>0, 'message'=>'物流公司网络异常，请稍后查询');
    }
    preg_match_all('/\\<p\\>&middot;(.*)\\<\\/p\\>/U', $resp, $arr);
    if (!isset($arr[1])) {
        return array( 'status'=>0, 'message'=>'查询失败，参数有误' );
    }else{
        foreach ($arr[1] as $key => $value) {
            $a = array();
            $a = explode('<br /> ', $value);
            $data[$key]['time'] = $a[0];
            $data[$key]['context'] = $a[1];
        }     
        return array( 'status'=>1, 'message'=>'ok','data'=> array_reverse($data));
    }
}

/**
 * 获取某个商品分类的 儿子 孙子  重子重孙 的 id
 * @param type $cat_id
 */
function getCatGrandson ($cat_id)
{
    $GLOBALS['catGrandson'] = array();
    $GLOBALS['category_id_arr'] = array();
    // 先把自己的id 保存起来
    $GLOBALS['catGrandson'][] = $cat_id;
    // 把整张表找出来
    $GLOBALS['category_id_arr'] = M('GoodsCategory')->cache(true,TPSHOP_CACHE_TIME)->getField('id,parent_id');
    // 先把所有儿子找出来
    $son_id_arr = M('GoodsCategory')->where("parent_id = $cat_id")->cache(true,TPSHOP_CACHE_TIME)->getField('id',true);
    foreach($son_id_arr as $k => $v)
    {
        getCatGrandson2($v);
    }
    return $GLOBALS['catGrandson'];
}

/**
 * 获取某个文章分类的 儿子 孙子  重子重孙 的 id
 * @param type $cat_id
 */
function getArticleCatGrandson ($cat_id)
{
    $GLOBALS['ArticleCatGrandson'] = array();
    $GLOBALS['cat_id_arr'] = array();
    // 先把自己的id 保存起来
    $GLOBALS['ArticleCatGrandson'][] = $cat_id;
    // 把整张表找出来
    $GLOBALS['cat_id_arr'] = M('ArticleCat')->getField('cat_id,parent_id');
    // 先把所有儿子找出来
    $son_id_arr = M('ArticleCat')->where("parent_id = $cat_id")->getField('cat_id',true);
    foreach($son_id_arr as $k => $v)
    {
        getArticleCatGrandson2($v);
    }
    return $GLOBALS['ArticleCatGrandson'];
}

/**
 * 递归调用找到 重子重孙
 * @param type $cat_id
 */
function getCatGrandson2($cat_id)
{
    $GLOBALS['catGrandson'][] = $cat_id;
    foreach($GLOBALS['category_id_arr'] as $k => $v)
    {
        // 找到孙子
        if($v == $cat_id)
        {
            getCatGrandson2($k); // 继续找孙子
        }
    }
}

function fenleitop ($cat_id)
{
    $GLOBALS['fenlei'] = array();
    $GLOBALS['category_id_arr'] = array();
	$path ='0_'.$cat_id;
    // 先把自己的id 保存起来
    $GLOBALS['fenlei'][] = $cat_id;
    // 先把所有儿子找出来
	M('GoodsCategory')->where('id='.$cat_id)->save([
		'parent_id_path'=>$path,
		'level'=>1
	]);
    $son_id_arr = M('GoodsCategory')->where("parent_id = $cat_id")->cache(true,TPSHOP_CACHE_TIME)->getField('id',true);
    foreach($son_id_arr as $k => $v)
    {
		$path=$path.'_'.$v; //二级分类
		M('GoodsCategory')->where('id='.$v)->save([
			'parent_id_path'=>$path,
			'level'=>2
		]);
		
		$erzi=M('GoodsCategory')->where("parent_id = $v")->cache(true,TPSHOP_CACHE_TIME)->getField('id',true);
		foreach($erzi as $vs){
			$paths=$path.'_'.$vs; //三级分类
			M('GoodsCategory')->where('id='.$vs)->save([
				'parent_id_path'=>$paths,
				'level'=>3
			]);
			//$path=$path.'_'.$v;
		}
		
		$path ='0_'.$cat_id;
    }


}

/**
 * 递归调用找到 重子重孙
 * @param type $cat_id
 */
function getArticleCatGrandson2($cat_id)
{
    $GLOBALS['ArticleCatGrandson'][] = $cat_id;
    foreach($GLOBALS['cat_id_arr'] as $k => $v)
    {
        // 找到孙子
        if($v == $cat_id)
        {
            getArticleCatGrandson2($k); // 继续找孙子
        }
    }
}

/**
 * 查看某个用户购物车中商品的数量
 * @param type $user_id
 * @param type $session_id
 * @return type 购买数量
 */
function cart_goods_num($user_id = 0,$session_id = '')
{
    $where = " session_id = '$session_id' ";
    $user_id && $where .= " or user_id = $user_id ";
    // 查找购物车数量
    $cart_count =  M('Cart')->where($where)->sum('goods_num');
    $cart_count = $cart_count ? $cart_count : 0;
    return $cart_count;
}

/**
 * 获取商品库存
 * @param type $goods_id 商品id
 * @param type $key  库存 key
 */
function getGoodNum($goods_id,$key)
{
    if(!empty($key))
        return  M("SpecGoodsPrice")->where("goods_id = $goods_id and `key` = '$key'")->getField('store_count');
}
 
/**
 * 获取缓存或者更新缓存
 * @param string $config_key 缓存文件名称
 * @param array $data 缓存数据  array('k1'=>'v1','k2'=>'v3')
 * @return array or string or bool
 */
function tpCache($config_key,$data = array()){
    $param = explode('.', $config_key);
    if(empty($data)){
        //如$config_key=shop_info则获取网站信息数组
        //如$config_key=shop_info.logo则获取网站logo字符串
        $config = F($param[0],'',TEMP_PATH);//直接获取缓存文件
        if(empty($config)){
            //缓存文件不存在就读取数据库
            $res = D('config')->where("inc_type='$param[0]'")->select();
            if($res){
                foreach($res as $k=>$val){
                    $config[$val['name']] = $val['value'];
                }
                F($param[0],$config,TEMP_PATH);
            }
        }
        if(count($param)>1){
            return $config[$param[1]];
        }else{
            return $config;
        }
    }else{
        //更新缓存
        $result =  D('config')->where("inc_type='$param[0]'")->select();
        if($result){
            foreach($result as $val){
                $temp[$val['name']] = $val['value'];
            }
            foreach ($data as $k=>$v){
                $newArr = array('name'=>$k,'value'=>trim($v),'inc_type'=>$param[0]);
                if(!isset($temp[$k])){
                    M('config')->add($newArr);//新key数据插入数据库
                }else{
                    if($v!=$temp[$k])
                        M('config')->where("name='$k'")->save($newArr);//缓存key存在且值有变更新此项
                }
            }
            //更新后的数据库记录
            $newRes = D('config')->where("inc_type='$param[0]'")->select();
            foreach ($newRes as $rs){
                $newData[$rs['name']] = $rs['value'];
            }
        }else{
            foreach($data as $k=>$v){
                $newArr[] = array('name'=>$k,'value'=>trim($v),'inc_type'=>$param[0]);
            }
            M('config')->addAll($newArr);
            $newData = $data;
        }
        return F($param[0],$newData,TEMP_PATH);
    }
}

/**
 * 记录帐户变动
 * @param   int     $user_id        用户id
 * @param   float   $user_money     可用余额变动
 * @param   int     $pay_points     消费积分变动
 * @param   string  $desc    变动说明
 * @param   float   distribut_money 分佣金额
 */
function accountLog($user_id, $user_money = 0,$pay_points = 0, $desc = '',$distribut_money = 0,$order_id = 0,$order_amount=0){
    $basic=tpCache("basic");
    $no_integral_date = $basic['no_integral_date'];
    if($no_integral_date){
        $no_integral_date = explode('~',$no_integral_date);
        $no_integral_date1 = strtotime($no_integral_date[0]);
        $no_integral_date2 = strtotime($no_integral_date[1]);
        $now = time();
        if(($now > $no_integral_date1) && ($now < $no_integral_date2)){ //跳过不产生积分的日期
            return false;
        }
    }


    /* 插入帐户变动记录 */
    $account_log = array(
        'user_id'       => $user_id,
        'user_money'    => $user_money,
        'pay_points'    => $pay_points,
        'change_time'   => time(),
        'desc'   => $desc,
        'order_id'   => $order_id
    );
	$pd=M('users')->where('user_id='.$user_id)->getField('pay_points');
	$pay_points=($pd+$pay_points)>0 ? $pay_points : 0;
    /* 更新用户信息 */
    if($order_amount){
        $sql = "UPDATE __PREFIX__users SET user_money = user_money + $user_money," .
            " pay_points = pay_points + $pay_points,total_amount = total_amount + $order_amount, distribut_money = distribut_money + $distribut_money WHERE user_id = $user_id";
    }else{
        $sql = "UPDATE __PREFIX__users SET user_money = user_money + $user_money," .
            " pay_points = pay_points + $pay_points, distribut_money = distribut_money + $distribut_money WHERE user_id = $user_id";
    }

    if( D('users')->execute($sql)){
    	M('account_log')->add($account_log);
        return true;
    }else{
        return false;
    }
}

/**
 * 记录商家的帐户变动
 * @param   int     $store_id        用户id
 * @param   float   $user_money     可用余额变动
 * @param   string  $desc    变动说明
 * @return  bool
 */
function storeAccountLog($store_id, $store_money = 0,$pending_money,$desc = '',$order_id = 0){
    /* 插入帐户变动记录 */
    $account_log = array(
        'store_id'       => $store_id,
        'store_money'    => $store_money, // 可用资金
        'pending_money'    => $pending_money, // 未结算资金
        'change_time'   => time(),
        'desc'   => $desc,
        'order_id'   => $order_id,
    );
    /* 更新店铺信息 */
    $sql = "UPDATE __PREFIX__store SET store_money = store_money + $store_money,store_moneys = store_moneys + $store_money WHERE store_id = $store_id";
    if( D('users')->execute($sql)){
    	M('account_log_store')->add($account_log);
        return true;
    }else{
        return false;
    }
}

/**
 * 订单操作日志
 * 参数示例
 * @param type $order_id  订单id
 * @param type $action_note 操作备注
 * @param type $status_desc 操作状态  提交订单, 付款成功, 取消, 等待收货, 完成
 * @param type $user_id  用户id 默认为管理员
 * @return boolean
 */
function logOrder($order_id,$action_note,$status_desc,$user_id = 0,$user_type = 0,$mygoods='')
{
    $status_desc_arr = array('提交订单', '付款成功', '取消', '等待收货', '完成','退货');
    // if(!in_array($status_desc, $status_desc_arr))
    // return false;

    $order = M('order')->where("order_id = $order_id")->find();
    $action_info = array(
        'order_id'        =>$order_id,
        'action_user'     =>$user_id,
        'user_type'       =>$user_type,		
        'order_status'    =>$order['order_status'],
        'shipping_status' =>$order['shipping_status'],
        'pay_status'      =>$order['pay_status'],
        'action_note'     => $action_note,
		'goods_ids'       =>$mygoods,
        'status_desc'     =>$status_desc, //''
        'log_time'        =>time(),
    );
    return M('order_action')->add($action_info);
}

/*
 * 获取地区列表
 */
function get_region_list(){
    //获取地址列表 缓存读取
    if(!S('region_list')){
        $region_list = M('region')->select();
        $region_list = convert_arr_key($region_list,'id');        
        S('region_list',$region_list);
    }

    return $region_list ? $region_list : S('region_list');
}
/*
 * 获取用户地址列表
 */
function get_user_address_list($user_id){
    $lists = M('user_address')->where(array('user_id'=>$user_id))->select();
    return $lists;
}

/*
 * 获取指定地址信息
 */
function get_user_address_info($user_id,$address_id){
    $data = M('user_address')->where(array('user_id'=>$user_id,'address_id'=>$address_id))->find();
    return $data;
}
/*
 * 获取用户默认收货地址
 */
function get_user_default_address($user_id){
    $data = M('user_address')->where(array('user_id'=>$user_id,'is_default'=>1))->find();
    return $data;
}
/**
 * 获取订单状态的 中文描述名称
 * @param type $order_id  订单id
 * @param type $order     订单数组
 * @return string
 */
function orderStatusDesc($order_id = 0, $order = array())
{
    if(empty($order))
        $order = M('Order')->where("order_id = $order_id")->find();

    // 货到付款
    if($order['pay_code'] == 'cod')
    {
        if(in_array($order['order_status'],array(0,1)) && $order['shipping_status'] == 0)
            return 'WAITSEND'; //'待发货',
    }
    else // 非货到付款
    {
        if($order['pay_status'] == 0 && $order['order_status'] == 0)
            return 'WAITPAY'; //'待支付',
        if($order['pay_status'] == 1 &&  in_array($order['order_status'],array(0,1)) && $order['shipping_status'] != 1)
            return 'WAITSEND'; //'待发货',
    }
    if(($order['shipping_status'] == 1) && ($order['order_status'] == 1))
        return 'WAITRECEIVE'; //'待收货',
    if($order['order_status'] == 2)
        return 'WAITCCOMMENT'; //'已完成待评价',
    if($order['order_status'] == 3)
        return 'CANCEL'; //'已取消',
    if($order['order_status'] == 4)
        return 'FINISH'; //'已完成',
    if($order['order_status'] == 5)
        return 'CANCELLED'; //'已作废',
    return 'OTHER';
}

/**
 * 获取订单状态的 显示按钮
 * @param type $order_id  订单id
 * @param type $order     订单数组
 * @return array()
 */
function orderBtn($order_id = 0, $order = array())
{
    if(empty($order))
        $order = M('Order')->where("order_id = $order_id")->find();
    /**
     *  订单用户端显示按钮
    去支付     AND pay_status=0 AND order_status=0 AND pay_code ! ="cod"
    取消按钮  AND pay_status=0 AND shipping_status=0 AND order_status=0
    确认收货  AND shipping_status=1 AND order_status=0
    评价      AND order_status=1
    查看物流  if(!empty(物流单号))
     */
    $btn_arr = array(
        'pay_btn' => 0, // 去支付按钮
        'cancel_btn' => 0, // 取消按钮
        'receive_btn' => 0, // 确认收货
        'comment_btn' => 0, // 评价按钮
        'shipping_btn' => 0, // 查看物流
        'return_btn' => 0, // 退货按钮 (联系客服)
    );


    // 货到付款
    if($order['pay_code'] == 'cod')
    {
        if(($order['order_status']==0 || $order['order_status']==1) && $order['shipping_status'] == 0) // 待发货
        {
            $btn_arr['cancel_btn'] = 1; // 取消按钮 (联系客服)
        }
        if($order['shipping_status'] == 1 && $order['order_status'] == 1) //待收货
        {
            $btn_arr['receive_btn'] = 1;  // 确认收货
            $btn_arr['return_btn'] = 1; // 退货按钮 (联系客服)
        }       
    }
    // 非货到付款
    else
    {
        if($order['pay_status'] == 0 && $order['order_status'] == 0) // 待支付
        {
            $btn_arr['pay_btn'] = 1; // 去支付按钮
            $btn_arr['cancel_btn'] = 1; // 取消按钮
        }
        if($order['pay_status'] == 1 && in_array($order['order_status'],array(0,1)) && $order['shipping_status'] == 0) // 待发货
        {
            $btn_arr['return_btn'] = 1; // 退货按钮 (联系客服)
        }
        if($order['pay_status'] == 1 && $order['order_status'] == 1  && $order['shipping_status'] == 1) //待收货
        {
            $btn_arr['receive_btn'] = 1;  // 确认收货
            $btn_arr['return_btn'] = 1; // 退货按钮 (联系客服)
        }
    }
    if($order['order_status'] == 2)
    {
        $btn_arr['comment_btn'] = 1;  // 评价按钮
        $btn_arr['return_btn'] = 1; // 退货按钮 (联系客服)
    }
    if($order['shipping_status'] != 0)
    {
        $btn_arr['shipping_btn'] = 1; // 查看物流
    }
    if($order['shipping_status'] == 2 && $order['order_status'] == 1) // 部分发货
    {            
        $btn_arr['return_btn'] = 1; // 退货按钮 (联系客服)
    }
    
    return $btn_arr;
}

/**
 * 给订单数组添加属性  包括按钮显示属性 和 订单状态显示属性
 * @param type $order
 */
function set_btn_order_status($order)
{
    $order_status_arr = C('ORDER_STATUS_DESC');
    $order['order_status_code'] = $order_status_code = orderStatusDesc(0, $order); // 订单状态显示给用户看的
    $order['order_status_desc'] = $order_status_arr[$order_status_code];
    $orderBtnArr = orderBtn(0, $order);
    return array_merge($order,$orderBtnArr); // 订单该显示的按钮
}


	/**
	 * 支付完成修改订单
	 * $order_sn 订单号
	 * $pay_status 默认1 为已支付
	 */
	function update_pay_status($param,$pay_status = 1)
	{
        if(isset($param['out_trade_no'])){
            $order_sn = substr($param['out_trade_no'],0,18);
        }else{
            $order_sn = $param;
        }

		if(stripos($order_sn,'recharge') !== false){
			//用户在线充值
			$count = M('recharge')->where("order_sn = '$order_sn' and pay_status = 0")->count();   // 看看有没已经处理过这笔订单  支付宝返回不重复处理操作
			if($count == 0) return false;
			$order = M('recharge')->where("order_sn = '$order_sn'")->find();
			M('recharge')->where("order_sn = '$order_sn'")->save(array('pay_status'=>1,'pay_time'=>time()));
			accountLog($order['user_id'],$order['account'],0,'会员在线充值');
		}else{
		   
			// 先查看一下 是不是 合并支付的主订单号
            $order_list = M('order')->where(['master_order_sn'=>$order_sn])->select();
            M('order')->where("master_order_sn = '$order_sn'")->save(array('pay_no'=>$param['pay_no']));
			if($order_list)
			{
				foreach($order_list as $key => $val)
					update_pay_status($val['order_sn'],1);
				return;
			}
			// 如果这笔订单已经处理过了
			$count = M('order')->where("order_sn = '$order_sn' and pay_status = 0")->count();   // 看看有没已经处理过这笔订单  支付宝返回不重复处理操作
			if($count == 0) return false;
			// 找出对应的订单
			$order = M('order')->where("order_sn = '$order_sn'")->find();
			// 修改支付状态  已支付
			M('order')->where("order_sn = '$order_sn'")->save(array('pay_status'=>1,'pay_time'=>time()));
		
			// 减少对应商品的库存
//			minus_stock($order['order_id']);
//			// 给他升级, 根据order表查看消费记录 给他会员等级升级 修改他的折扣 和 总金额
			update_user_level($order['user_id']);
			// 记录订单操作日志
			logOrder($order['order_id'],'订单付款成功','付款成功',$order['user_id'],2);
			//分销设置
//			M('rebate_log')->where("order_id = {$order['order_id']}")->save(array('status'=>1));
//			// 成为分销商条件
//			$distribut_condition = tpCache('distribut.condition');
//			if($distribut_condition == 1)  // 购买商品付款才可以成为分销商
//				M('users')->where("user_id=". $order['user_id'])->save(array('is_distribut'=>1));
//
//			// 给商家待结款字段加上
//			$order_settlement = order_settlement($order['order_id']);
//			M('store')->where("store_id = {$order['store_id']}")->setInc('pending_money',$order_settlement[0]['store_settlement']); // 店铺 待结算资金 累加
//			// 赠送积分
//			order_give($order);// 调用送礼物方法, 给下单这个人赠送相应的礼物
//			sendSms_notice($order['store_id'],$order['order_id']);
//			//拼团处理
//			update_pintuan_info($order['order_id']);
		}
	}
	//拼团操作函数处理
	function update_pintuan_info($order_id){
		$order = M('order')->where("order_id = '$order_id'")->find();
        if($order['order_prom_id'] == 0){
            //新开团
            $goods_id = M('order_goods')->where(array('order_id'=>$order['order_id']))->getField('goods_id');
            $ptg = M('goods')->find($goods_id);
            //判断拼团时间
            if(time() > strtotime($ptg['pt_stop_time'])){
                            //去退款                                
                M('order')->where(array('order_id'=>$order_id))->save(array('pint_stu'=>2));
                return array('status'=> '-1','msg'=>'该拼团活动不存在或已结束');
            }
            $pintData = array(
                'goods_id'          => $ptg['goods_id'],
                'store_id'          => $ptg['store_id'],
                'user_id'           => $order['user_id'],
                'users_id'          => $order['user_id'],
                'pint_price'        => $ptg['pt_price'],
                'pint_star_time'    => time(),
                'pint_stop_time'    => (time()+3600*$ptg['pt_keep_time']),
                'pint_user_num'     => $ptg['pt_man_num'],
                'pint_status'       => 0,
                'pint_user_num_now' => 1,
            );
            $pint_id = M('pint')->data($pintData)->add();
            $order_id = $order['order_id'];
            M('order')->where(array('order_id'=>$order_id))->save(array('order_prom_id'=>$pint_id));
            M('order_goods')->where(array('order_id'=>$order_id))->save(array('prom_id'=>$pint_id));
        }else{
            //加入团
            $pint_id = $order['order_prom_id'];
            $pt = M('pint')->find($pint_id);
            $order_id = $order['order_id'];
            $syrs = $pt['pint_user_num'] - $pt['pint_user_num_now'];
            $sysj = $pt['pint_stop_time'] - time();
            if(!$pt || $syrs<= 0 || $sysj<=0){
               //去退款吧
                M('order')->where(array('order_id'=>$order_id))->save(array('pint_stu'=>2));
                return array('status'=>-1,'msg'=>'该拼团活动不存在或已结束');
            }
                        
            $pintData = array(
                'users_id'          => $pt['users_id'].','.$order['user_id'],
                'pint_status'       => 0,
                'pint_user_num_now' => $pt['pint_user_num_now']+1,
            );
            M('pint')->where(array('pint_id'=>$pt['pint_id']))->data($pintData)->save();
            M('order')->where(array('order_id'=>$order_id))->save(array('order_prom_id'=>$pint_id));
            M('order_goods')->where(array('order_id'=>$order_id))->save(array('prom_id'=>$pint_id));
            $pit = M('pint')->find($pt['pint_id']);
            if($pit['pint_user_num'] == $pit['pint_user_num_now']){
                //拼团成功
                M('pint')->where(array('pint_id'=>$pt['pint_id']))->data(array('pint_status'=>1))->save();
                $pt_numed = M('order_goods')->where(array('goods_id'=>$pt['goods_id'],'prom_type'=>'101','prom_id'=>$pt['pint_id']))->getField('COUNT(goods_num)');
                M('goods')->where(array('goods_id'=>$pt['goods_id']))->setINc('pt_numed',$pt_numed);
            }
            // echo '成功2';
        }			
	}
    //更新充值表信息
    function updata_recharge_info ($order_sn) {
		
        $data = array('pay_time'=>time(), 'pay_status'=>1);
    	$k = M('recharge')->where(array('order_sn'=>$order_sn))->save($data);
	
		$order = M('recharge')->where(array('order_sn'=>$order_sn))->find();
		M('users')->where(array('user_id'=>$order['user_id']))->setInc('user_money', $order['account']);
		
		$log = array();
		$log['user_id'] = $order['user_id'];
		$log['order_sn'] = $order_sn;
		$log['order_id'] = $order['order_id'];
		$log['pay_points'] = 0;
		$log['user_money'] = $order['account'];
		$log['frozen_money'] = 0;
		$log['change_time'] = time();
		$log['desc'] = '用户充值';
		D('account_log')->add($log);
    }


    /**
     * 订单确认收货
     * @param $id   订单id
     */
    function confirm_order($id,$user_id = 0){
        $where = "order_id = $id";
        $user_id && $where .= " and user_id = $user_id ";
        
        $order = M('order')->where($where)->find();

        if($order['order_status'] != 1)
            return array('status'=>-1,'msg'=>'该订单不能收货确认');
        
        $data['order_status'] = 2; // 已收货        
        $data['pay_status'] = 1; // 已付款        
        $data['confirm_time'] = time(); //  收货确认时间
        if($order['pay_code'] == 'cod'){
        	$data['pay_time'] = time();
        }
        $row = M('order')->where(array('order_id'=>$id))->save($data);
        if(!$row)        
            return array('status'=>-3,'msg'=>'操作失败');                
        
        //分销设置
        M('rebate_log')->where("order_id = $id and status < 4")->save(array('status'=>2,'confirm'=>time()));
               
        return array('status'=>1,'msg'=>'操作成功');
    }

/**
 * 给订单送券送积分 送东西
 */
function order_give($order)
{
	$order_goods = M('order_goods')->where("order_id=".$order['order_id'])->cache(true)->select();
	//查找购买商品送优惠券活动
	foreach ($order_goods as $val)
       {
		if($val['prom_type'] == 3)
                {
			$prom = M('prom_goods')->where("store_id = {$order['store_id']} and type=3 and id=".$val['prom_id'])->find();
			if($prom)
                        {
				$coupon = M('coupon')->where("id=".$prom['expression'])->find();//查找优惠券模板
				if($coupon && $coupon['createnum']>0)
                                {					                                        
                                        $remain = $coupon['createnum'] - $coupon['send_num'];//剩余派发量
                                        if($remain > 0)                                            
                                        {
                                            $data = array('cid'=>$coupon['id'],'type'=>$coupon['type'],'uid'=>$order['user_id'],'send_time'=>time());
                                            M('coupon_list')->add($data);       
                                            M('Coupon')->where("id = {$coupon['id']}")->setInc('send_num'); // 优惠券领取数量加一
                                         }
				}
		 	}
		 }
	}
	
	//查找订单满额送优惠券活动
	$pay_time = $order['pay_time'];
	$prom = M('prom_order')->where("store_id = {$order['store_id']} and type>1 and end_time>$pay_time and start_time<$pay_time and money<=".$order['order_amount'])->order('money desc')->find();
	if($prom){
		if($prom['type']==3){
			$coupon = M('coupon')->where("id=".$prom['expression'])->find();//查找优惠券模板
			if($coupon){
				if($coupon['createnum']>0)
                               {
					$remain = $coupon['createnum'] - $coupon['send_num'];//剩余派发量
                                        if($remain > 0)
                                        {
                                            $data = array('cid'=>$coupon['id'],'type'=>$coupon['type'],'uid'=>$order['user_id'],'send_time'=>time(), 'store_id'=>$order['store_id']);
                                            M('coupon_list')->add($data);           
                                            M('Coupon')->where("id = {$coupon['id']}")->setInc('send_num'); // 优惠券领取数量加一
                                        }				
				}
			}
		}else if($prom['type']==2){
			accountLog($order['user_id'], 0 , $prom['expression'] ,"订单活动赠送积分");
		}
	}
    $points = M('order_goods')->where("order_id = {$order[order_id]}")->sum("give_integral * goods_num");
    $points && accountLog($order['user_id'], 0,$points,"下单赠送积分");
}


/**
 * 查看商品是否有活动
 * @param goods_id 商品ID
 */

function get_goods_promotion($goods_id,$user_id=0,$price=0,$goods_spec='ok'){
	$now = time();
	$goods = M('goods')->where("goods_id=$goods_id")->find();
	$where = "end_time>$now and start_time<$now and id=".$goods['prom_id'];
	//shadow
	$goods['shop_price']=empty($price) ? $goods['shop_price'] : $price; // 如果商品规格没有指定价格则用商品原始价格

	$prom['price'] = $goods['shop_price'];
	$prom['prom_type'] = $goods['prom_type'];
	$prom['prom_id'] = $goods['prom_id']; 
	$prom['is_end'] = 0;
	
	if($goods['prom_id']>0){//优惠促销
		$parse_type = array('0'=>'直接打折','1'=>'减价优惠','2'=>'固定金额出售','3'=>'买就赠优惠券','4'=>'买M件送N件');
		$prominfo = M('prom_goods')->where($where)->find();
		if(!empty($prominfo)){
			if($prominfo['type'] == 0){
				if($prominfo['zd']==1){
					$prom['price'] = geshi($goods['shop_price']*($prominfo['expression']/100));//整店打折优惠
					$prom['prom_msg'] ='全店打折';$prom['zd'] = 1;
				}else{
					if(strpos($prominfo['goods_key'],$goods_spec) !== false){
						$prom['price'] = geshi($goods['shop_price']*($prominfo['expression']/100));//单规格打折优惠
						$prom['prom_msg'] =huodong_name($prominfo['type'],$prominfo['expression']);
					}
					 
				}
				//echo json_encode($prom['price']);exit;
			}elseif($prominfo['type'] == 1){
				if(strpos($prominfo['goods_key'],$goods_spec) !== false){
					$prom['price'] = $goods['shop_price']-$prominfo['expression'];//减价优惠
					$prom['prom_msg'] =huodong_name($prominfo['type'],$prominfo['expression']);
				}
				
			}elseif($prominfo['type']==2){
				if(strpos($prominfo['goods_key'],$goods_spec) !== false){
					$prom['price'] = $prominfo['expression'];//固定金额优惠
					$prom['prom_msg'] =huodong_name($prominfo['type'],$prominfo['expression']);
				}
			}
		}
	}
	
	if(!empty($prominfo)){
		$prom['start_time'] = $prominfo['start_time'];
		$prom['end_time'] = $prominfo['end_time'];
	}else{
		$prom['prom_type'] = $prom['prom_id'] = 0 ;//活动已过期
		$prom['is_end'] = 1;//已结束
	}
	
	// if($prom['prom_id'] == 0){
	// 	M('goods')->where("goods_id=$goods_id")->save($prom);
	// }
	return $prom;
}

function get_goods_huodong($goods_id,$goods_spec='ok'){  //获取活动商品价格属性 
	$now = time();
	$goods = M('goods')->where("goods_id=$goods_id")->find();
// 	$where = "$now<end_time and $now>start_time and id=".$goods['prom_id'];
	$where = 'id='.$goods['prom_id'];
	$spec_price=M('spec_goods_price')->where('goods_id='.$goods_id.' and `key`="'.$goods_spec.'"')->find();

	$prom['goods_name'] = $goods['goods_name'];
	$prom['price'] = sanwei($spec_price['price']*($goods['floating']/100));
	$prom['prom_id'] = $goods['prom_id'];
	$prom['key_name'] = $spec_price['key_name'];
	$prom['prom_msg'] ='';
	$prom['sku'] = $spec_price['sku'];
	$prom['zd'] = 0;
	$prom['is_end'] = 0;
	
	if($goods['prom_id']>0){//优惠促销
		$prominfo = M('prom_goods')->where($where)->find();
		if(!empty($prominfo) && ($prominfo['end_time']>$now && $prominfo['start_time']< $now)){
			if($prominfo['type'] == 0){
			    
				if($prominfo['zd']==1){
				    // dump(geshi($prom['price']));
					$prom['price'] = geshi(geshi($prom['price'])*($prominfo['expression']/100));//整店打折优惠
					$prom['prom_msg'] ='全店打折';$prom['zd']=1;
				}else{
					if(strpos($prominfo['goods_key'],(string)$goods_spec) !== false){
						$prom['price'] = geshi($prom['price']*($prominfo['expression']/100));//单规格打折优惠
						$prom['prom_msg'] =huodong_name($prominfo['type'],$prominfo['expression']);
					}
				}
			}elseif($prominfo['type'] == 1){
				if(strpos($prominfo['goods_key'],(string)$goods_spec) !== false){
					$prom['price'] = $prom['price']-$prominfo['expression'];//减价优惠
					$prom['prom_msg'] =huodong_name($prominfo['type'],$prominfo['expression']);
				}
				
			}elseif($prominfo['type']==2){
                if(strpos($prominfo['goods_key'],(string)$goods_spec) !== false){
                    $prom['price'] = $prominfo['expression'];//固定金额优惠
                    $prom['prom_msg'] =huodong_name($prominfo['type'],$prominfo['expression']);
                }

            }elseif($prominfo['type']==4){
                if(strpos($prominfo['goods_key'],(string)$goods_spec) !== false){
                    $prom['price'] = $prom['price'];//固定金额优惠
                    $prom['prom_msg'] =huodong_name($prominfo['type'],$prominfo['expression']);
                }

            }elseif($prominfo['type']==5){
                if(strpos($prominfo['goods_key'],(string)$goods_spec) !== false){
                    $prom['price'] = geshi($prom['price']*($prominfo['expression']/100));
                    $prom['prom_msg'] =huodong_name($prominfo['type'],$prominfo['expression']);
                }
            }
		}
	}
	
	if(!empty($prominfo)){
		$prom['start_time'] = $prominfo['start_time'];
		$prom['end_time'] = $prominfo['end_time'];
	}else{
		$prom['prom_type'] = $prom['prom_id'] = 0 ;//活动已过期
		$prom['is_end'] = 1;//已结束
	}
	return $prom;
}

/**
 * 查看订单是否满足条件参加活动
 * @param order_amount 订单应付金额
 * @param store_id  店铺id
 */
function get_order_promotion($order_amount , $store_id){
	//20190310 维亚轩  修复商家后台添加订单报错问题
	if(empty($store_id)){
		
		$store_id=0;
	}
	//20190310 维亚轩  修复商家后台添加订单报错问题
	$parse_type = array('0'=>'满额打折','1'=>'满额优惠金额','2'=>'满额送倍数积分','3'=>'满额送优惠券','4'=>'满额免运费');
	$now = time();
	$prom = M('prom_order')->where("store_id = $store_id and type < 2 and end_time > $now and start_time < $now and money <= $order_amount")->order('money desc')->find();
	$res = array('order_amount'=>$order_amount,'order_prom_id'=>0,'order_prom_amount'=>0);
	if($prom){
		if($prom['type'] == 0){
			$res['order_amount']  = round($order_amount*($prom['expression']/100),2);//满额打折
			$res['order_prom_amount'] = $order_amount - $res['order_amount'] ;
			$res['order_prom_id'] = $prom['id'];
		}elseif($prom['type'] == 1){
			$res['order_amount'] = $order_amount- $prom['expression'];//满额优惠金额
			$res['order_prom_amount'] = $prom['expression'];
			$res['order_prom_id'] = $prom['id'];
		}
	}
	return $res;
}

//计算订单应收金额
function order_price($order_id){
	$orders=M('order')->where('order_id='.$order_id)->find();
	$orders_goods=M('order_goods')->where('order_id='.$order_id)->select();
	$points_count=0;
	if($orders['dai_type']==2){
		$points_count=$orders_goods[0]['points']*$orders['order_amount']/100; //平台扣点
	}else{
		foreach($orders_goods as $v){
			$points_count+=$v['points']*$v['member_goods_price']*$v['goods_num']/100; //平台扣点
		}
	}
	
	return [
		'coupon_price'=>$orders['coupon_price'], //使用优惠券金额
		'integral'=>$orders['integral'], //使用积分
		'integral_money'=>$orders['integral_money'], //使用积分金额
		'order_amount'=>$orders['order_amount'], //应收金额
		'total_amount'=>$orders['total_amount']+$orders['yijia_heji'], //订单总金额
		'coupon_price'=>$orders['coupon_price'], //优惠券金额
		'points_count'=>sanwei($points_count), //平台扣点
		'yinshou_price'=>$orders['order_amount']+$orders['yijia_heji']-sanwei($points_count)+$orders['integral_money'] //最终应收金额
	];
}
//计算订单应收金额
function store_order_price($order_id){
	$orders=M('order')->where('order_id='.$order_id)->find();
	$orders_goods=M('order_goods')->where('order_id='.$order_id)->select();
	$points_count=0;
	if($orders['dai_type']==2){
		$points_count=$orders_goods[0]['points']*$orders['order_amount']/100; //平台扣点
	}else{
		foreach($orders_goods as $v){
			$points_count+=$v['points']*$v['member_goods_price']*$v['goods_num']/100; //平台扣点
		}
	}
	
	return [
		'integral'=>$orders['integral'], //使用积分
		'integral_money'=>$orders['integral_money'], //使用积分金额
		'order_amount'=>$orders['order_amount'], //应收金额
		'points_count'=>sanwei($points_count), //平台扣点
		'yinshou_price'=>$orders['order_amount']-sanwei($points_count)+$orders['integral_money'] //最终应收金额
	];
}
/**
 * 计算订单金额
 * @param type $user_id  用户id
 * @param type $order_goods  购买的商品
 * @param type $shipping_code  物流code  数组
 * @param type $shipping_price  数组 物流费用, 如果传递了物流费用 就不在计算物流费
 * @param type $province  省份
 * @param type $city 城市 
 * @param type $district 县
 * @param type $pay_points 积分   数组
 * @param type $user_money 余额
 * @param type $coupon_id  优惠券  数组
 * @param type $couponCode  优惠码 数组 
 * @param type $couponCode  优惠码 数组
 */ 
function calculate_price($user_id=0,$order_goods,$shipping_code = array(),$shipping_price = array(),$province=0,$city=0,$district=0,$pay_points=0,$user_money=0,$coupon_id = array(),$couponCode = array(),$payment,$admin_id=0)
{
    $cartLogic = new \WXAPI\Logic\CartLogic();
    $user = M('users')->where("user_id = $user_id")->find();// 找出这个用户
    
    if(empty($order_goods)) 
        return array('status'=>-9,'msg'=>'商品列表不能为空','result'=>'');
    
        // 判断使用积分 余额 
    if($admin_id==0){
    if($pay_points && ($pay_points > $user['pay_points']))
        return array('status'=>-5,'msg'=>"你的账户可用积分为:".$user['pay_points'],'result'=>''); // 返回结果状态  
    }
	 $time = time();
    if($user_money  && ($user_money > $user['user_money']))
       return array('status'=>-6,'msg'=>"余额不足",'result'=>''); // 返回结果状态 
    
        foreach($order_goods as $key => $val)
        {

                if(!empty($val['fenbu_koudian'])){
                    $val['fenbu_koudian'] = json_decode($val['fenbu_koudian'],true);
                    foreach ($val['fenbu_koudian'] as $k=>$v){

                        if($v['fenbu_id'] == $user['fenbu_id']){
                            if(!empty($v['fenbu_koudian'])){
                                $val['points'] = $v['fenbu_koudian'];
                                break;
                            }
                        }
                    }
                }
                // dump($val);
                // die;
                //判断是否存在活动，存在活动是否有设置扣点
                if($val['zd'] != 1){
                    if($val['prom_id'] > 0){
                        $prom = M('prom_goods')->where('id = '.$val['prom_id'].' and start_time <='.$time.' and end_time>='.$time.' and goods_key like "%'.$val['spec_key'].'%"')->getField('prom_kou');
                    
                        if(!empty($prom)){
                            if($prom > 0){
                                $val['points'] = $prom;
                                $order_goods[$key]['points'] = $prom;
                            }
                        }
                    }
                }else{
                    if($val['prom_id'] > 0){
                        $prom = M('prom_goods')->where('id = '.$val['prom_id'].' and start_time <='.$time.' and end_time>='.$time)->getField('prom_kou');
                        if(!empty($prom)){
                            if($prom > 0){
                                $val['points'] = $prom;
                                $order_goods[$key]['points'] = $prom;
                            }
                        }
                    }
                }
                
                
                
                $is_pint = $pint_id = 0;
                $order_goods[$key]['goods_fee'] = $val['goods_num'] * $val['member_goods_price'];    // 小计
                $yijia = 0;
                if($val['stop_yijia'] == 1){
                    $yijia = yj_price($val['goods_id'],$val['member_goods_price'],$user['fenbu_id']);
                }
				$order_goods[$key]['yijia_heji'] =  ($val['goods_num'] * $yijia) ;
                $order_goods[$key]['store_count']  = getGoodNum($val['goods_id'],$val['spec_key']); // 最多可购买的库存数量
				$order_goods[$key]['kou_price']  =sanwei($order_goods[$key]['goods_fee']* $val['points']/100); // 平台收益
				if($admin_id==0){
                if($order_goods[$key]['store_count'] <= 0 || $order_goods[$key]['store_count']<$val['goods_num']) {
                	return array('status'=>-10,'msg'=>$order_goods[$key]['goods_name']."库存不足,请重新选择下单!",'result'=>'');  
                }
				}
                
                $cut_fee     += $val['goods_num'] * $val['market_price'] - $val['goods_num'] * $val['member_goods_price']; // 共节约
                $anum        += $val['goods_num']; // 购买数量
                $goods_price += $order_goods[$key]['goods_fee']; // 商品总价
				$kou_price_s += $order_goods[$key]['kou_price']; //商家添加订单产品
				$yijia_heji_s += $order_goods[$key]['yijia_heji']; //平台溢价合计
				$kou_price[$val['store_id']]  +=$order_goods[$key]['kou_price'];
				$yijia_heji[$val['store_id']]  +=$order_goods[$key]['yijia_heji']; // 溢价总价
                $store_goods_price[$val['store_id']] += $order_goods[$key]['goods_fee']; // 每个商家 的商品总价
        }
        
        // 因为当前方法在没有user_id 的情况下也可以调用, 因此 需要判断用户id
        if($user_id)
        {
            // 循环优惠券
            foreach($coupon_id as $key => $value){
                $coupon_result = $cartLogic->getCouponMoney($user_id, $value,1); // 下拉框方式选择优惠券
                $store_coupon_price[$key] = $coupon_result;
			}
            //循环优惠券码
            foreach($couponCode as $key => $value)
            {
                if(empty($value))
                    continue;
                $coupon_result = $cartLogic->getCouponMoneyByCode($value,$store_goods_price[$key],$key); // 根据 优惠券 号码获取的优惠券
                if($coupon_result['status'] < 0) 
                  return $coupon_result;
                $store_coupon_price[$key] = $coupon_result['result'];
            }
        }
		
        // 所有 商家优惠券抵消金额
        $coupon_price = array_sum($store_coupon_price); 
        $order_price = array_sum($store_goods_price);
        //存在平台优惠卷，按比例计算每个商家应付金额
        if(isset($store_coupon_price[0])){
            foreach($store_goods_price as $k => $v){
                $store_coupon_price[$k] = round(($v/$order_price)*$coupon_price,2); //优惠券分摊后金额
            }
        }
        
        // 计算每个商家的应付金额
        foreach($store_goods_price as $k => $v){
            //$store_order_amount[$k] = $v + $store_shipping_price[$k] - $store_coupon_price[$k]; // 应付金额 = 商品价格 + 物流费 - 优惠券
			$store_order_amount[$k] = $v - $store_coupon_price[$k]; // 应付金额 = 商品价格 + 物流费 - 优惠券
            $order_prom = get_order_promotion($store_order_amount[$k],$k); // 拿应付金额再去计算商家的订单活动  看看商家有没订单满额优惠活动
            $store_order_prom_id[$k] = $order_prom['order_prom_id']; // 订单优惠活动id
            $store_order_prom_amount[$k] = $order_prom['order_prom_amount']; // 订单优惠了多少钱
            $store_order_amount[$k] = $order_prom['order_amount']; // 订单优惠后是多少钱 得出  应付金额
        }

        // 应付金额 = 商品价格 + 物流费 - 优惠券    
        $order_amount = $goods_price - $coupon_price;
        // 订单总价 = 商品总价 + 物流总价
        $total_amount = $goods_price;
        
        // 积分支付 100 积分等于 1块钱 
        $integral_money = ($pay_points / tpCache('shopping.point_rate')); 
        $integral_money = ($integral_money > $order_amount) ? $order_amount : $integral_money; // 假设应付 1块钱 而用户输入了 200 积分 2块钱, 那么就让 $pay_points = 1块钱 等同于强制让用户输入1块钱
        $pay_points = $integral_money * tpCache('shopping.point_rate'); //以防用户使用过多积分的情况
        $order_amount = $order_amount - $integral_money; //  积分抵消应付金额
        
       // 余额支付原理等同于积分
       $user_money = ($user_money > $order_amount) ? $order_amount : $user_money;  
       $order_amount = $order_amount - $user_money; //  余额支付抵应付金额
	   
	   //判断是否是 余额支付  余额支付的话 改变订单应付款金额
	   if($payment=="balance"){
		   
		   $user_money=$order_amount;
		   $order_amount=0;
	   }   
		//if($user_money  && ($user_money > $user['user_money']))
		//	return array('status'=>-6,'msg'=>"余额不足:",'result'=>''); // 返回结果状态
		
        // 计算每个商家平摊积分余额  和 余额
        $sum_store_order_amount = array_sum($store_order_amount);
        foreach($store_order_amount as $k => $v){
            // 当前的应付金额 除以所有商家累加的应付金额,  算出当前应付金额的占比
            $proportion = $v / $sum_store_order_amount;
            if($pay_points > 0){
                $store_point_count[$k] = (int)($proportion * $pay_points);
                $store_order_amount[$k] -= $store_point_count[$k] / tpCache('shopping.point_rate'); // 每个商家减去对应积分抵消的余额
            }              
            if($user_money > 0){                
                $store_balance[$k] = round($proportion * $user_money,2); // 每个商家平摊用了多少余额  保留两位小数
                $store_order_amount[$k] -= $store_balance[$k]; // 每个商家减去余额支付抵消的
            }  
            $store_order_amount[$k] = round($store_order_amount[$k],2);
        } 
        // 如果出现除数 除不尽的, 则最后一位加一
        if($pay_points && array_sum($store_point_count) != $pay_points)
        {
            $store_point_count[$k] += 1;
            $store_order_amount[$k] -= (1 / tpCache('shopping.point_rate')); // 最后一个积分也算上去
        }
        // 20181015 增加判断并记录支付方式 亮 START
        if ($payment == "balance") {
            $pay_name = "余额支付";
        } elseif ($payment == "weixin") {
            $pay_name = "微信支付";
        }else{
            $pay_name = "货到付款";
        }
    // 20181015 增加判断并记录支付方式 亮 END
        //订单总价  应付金额  物流费  商品总价 节约金额 共多少件商品 积分  余额  优惠券
        $result = array(
            'total_amount'      => $total_amount, // 订单总价
            'order_amount'      => $order_amount, // 应付金额      只用于订单在没有参与优惠活动的时候价格是对的, 如果某个商家参与优惠活动 价格会有所变动      
            'goods_price'       => $goods_price, // 商品总价
			'kou_price_s'       => $kou_price_s, // 订单收益
			'yijia_heji_s'       => $yijia_heji_s, // 订单溢价
            'cut_fee'           => $cut_fee, // 共节约多少钱
			'kou_price'       => $kou_price, // 订单收益
            'anum'              => $anum, // 商品总共数量
            'integral_money'    => $integral_money,  // 积分抵消金额
            'user_money'        => $user_money, // 使用余额
            'coupon_price'      => $coupon_price,// 优惠券抵消金额
            'order_goods'       => $order_goods, // 商品列表 多加几个字段原样返回
            'shipping_price'    => 0, // 物流费
            'store_order_prom_amount'=>$store_order_prom_amount,// 订单优惠了多少钱
            'store_order_prom_id'=>$store_order_prom_id,// 订单优惠活动id
            'store_order_amount'=>$store_order_amount, // 订单优惠后是多少钱
            'store_shipping_price'=>0, //每个商家的物流费
            'store_coupon_price'=> $store_coupon_price, //每个商家的优惠券金额
            'store_goods_price' => $store_goods_price,//  每个店铺的商品总价
            'store_point_count' => $store_point_count, // 每个商家平摊使用了多少积分
            'store_balance'     => $store_balance, // 每个商家平摊用了多少余额
            'pint_id'           => $pint_id,
            'is_pint'           => $is_pint,
            'pay_name'           => $pay_name,
			'yijia_heji'           => $yijia_heji
        );    

    return array('status'=>1,'msg'=>"计算价钱成功",'result'=>$result); // 返回结果状态
}


/**
 * 订单结算
 * author:tian心
 * date:2016-08-28
 * @param $order_id  订单order_id
 * @param $rec_id 需要退款商品rec_id 
 */

function order_settlement($order_id,$rec_id = 0)
{   
    $point_rate = tpCache('shopping.point_rate');
    $point_rate = 1 / $point_rate; //积分换算比例
        
	$order = M('order')->where(array('order_id' => $order_id))->find();//订单详情
	if($order && $order['pay_status'] == 1){
		$order['store_settlement'] = $order['shipping_price'];//商家待结算初始金额
		$order_goods = M('order_goods a')
		->field('a.*,b.points')
		->join('ty_goods b on a.goods_id=b.goods_id')
		->where(array('order_id' => $order_id))->select();//订单商品列表

		$refund = $prom_and_coupon = $order['settlement'] = $order['store_settlement'] = $refund_integral = 0;
		/* 商家订单商品结算公式(独立商家一笔订单计算公式)
		*  均摊比例 = 这个商品总价/订单商品总价
		*  均摊优惠金额  = 均摊比例 *(代金券抵扣金额 + 优惠活动优惠金额)
		*  商品实际售卖金额  =  商品总价 - 购买此商品赠送积分 - 此商品分销分成 - 均摊优惠金额
		*  商品结算金额  = 商品实际售卖金额 - 商品实际售卖金额*此类商品平台抽成比例
		*  订单实际支付金额  =  订单商品总价 - 代金券抵扣金额 - 优惠活动优惠金额(跟用户使用积分抵扣，使用余额支付无关,积分在商家赠送时平台已经扣取)
		*
		*  整个订单商家结算所得金额  = 所有商品结算金额之和 + 物流费用(商家发货，物流费直接给商家)
		*  平台所得提成  = 所有商品提成之和
		*  商品退款说明 ：如果使用了积分，那么积分按商品均摊退回给用户，但使用优惠券抵扣和优惠活动优惠的金额此商品均摊的就不退了
		*  积分说明：积分在商家赠送时，直接从订单结算金中扣取该笔赠送积分可抵扣的金额
		*  优惠券赠送使用说明 ：优惠券在使用的时直接抵扣商家订单金额,无需跟平台结算，全场通用劵只有平台可以发放，所以由平台自付
		*  交易费率：例如支付宝，微信都会征收交易的千分之六手续费
		*/		
		foreach ($order_goods as $k=>$val){
			$settlement = $goods_amount = $val['member_goods_price']*$val['goods_num']; //此商品该结算金额初始值
						
			$settlement_rate = round($goods_amount/$order['goods_price'],4);//此商品占订单商品总价比例
			
			if($val['give_integral']>0){				
				$settlement = $settlement - $val['goods_num']*$val['give_integral'] * $point_rate;//减去购买该商品赠送积分
			}
			
			if($val['distribut']>0){
				$settlement = $settlement - $val['distribut']*$val['goods_num'];//减去分销分成金额
			}
			
			if($order['order_prom_amount']>0 || $order['coupon_price']>0){
				$prom_and_coupon = $settlement_rate*($order['order_prom_amount']+$order['coupon_price']);//均摊优惠金额  = 此商品总价/订单商品总价*优惠总额 
				$settlement = $settlement - $prom_and_coupon;//减去优惠券抵扣金额和优惠折扣
			}
		
			//$order_goods[$k]['goods_settlement'] = round($settlement,2) - round($settlement*$val['commission']/100,2);//每件商品该结算金额
			$order_goods[$k]['goods_settlement'] = round($settlement,2) - round($settlement*$val['points']/100,2);

			if($val['rec_id'] == $rec_id || $val['is_send'] == 3){
				$val['refund_integral'] = intval($order['integral']*$settlement_rate);//使用积分抵扣金额均摊  == 此商品需要退还用户积分
				$val['refund_settlement'] = $goods_amount - $prom_and_coupon - $val['refund_integral'] * $point_rate;//此商品实际需要退款金额
				if($val['give_integral'] > 0){
					$user_integral = M('users')->where(array('user_id'=>$order['user_id']))->getField('pay_points');//用户积分余额
					if($user_integral < $val['give_integral']*$val['goods_num']){
						$val['refund_settlement'] = $val['refund_settlement'] - $val['give_integral']*$val['goods_num']*$point_rate;//如果赠送积分被使用，那么从退款中扣除积分金额
						$val['give_integral'] = 0; //赠送积分已经从退款中扣除
					}else{
						$val['give_integral'] = $val['give_integral']*$val['goods_num'];//需要追回的赠送积分
					}
				}
				$refund += $val['refund_settlement']; //已经退款商品金额
				$refund_integral += $val['refund_integral'];//累计退还积分
				if($rec_id>0){
					return  $val; //直接返回需要退款的商品退款信息
				}			
			}else{
				$order['store_settlement'] += $order_goods[$k]['goods_settlement']; //订单所有商品结算所得金额之和
				$order['settlement'] += round($val['points']*$goods_amount/100,2);//平台抽成之和
				$order['give_integral'] +=  $val['give_integral']*$val['goods_num'];//订单赠送积分
				$order['distribut'] += $val['distribut']*$val['goods_num'];//订单分销分成
				$order['integral'] = $order['integral'] - $refund_integral;//订单使用积分
				$order['goods_amount'] += $goods_amount;//订单商品总价
			}
			
		}
		//$order_goods[$k]['settlement'] = round($settlement,2) - $order_goods[$k]['goods_settlement'];//平台抽成所得

		$order['settlement'] = $order['settlement']; //整个订单结算平台所得金额
		$order['store_settlement'] += $order['shipping_price'];//整个订单商家结算所得金额
		//$order['store_settlement'] = round($order['store_settlement']*(1-0.006),2);//支付手续费
	}
	
	return array($order,$order_goods);
}

/**
 * 获取商品一二三级分类
 * @return type
 */
function get_goods_category_tree(){
	$result = array();
	$cat_list = M('goods_category')->where("is_show = 1")->order('sort_order')->cache(true)->select();//所有分类
	
	foreach ($cat_list as $val){
		if($val['level'] == 2){
			$arr[$val['parent_id']][] = $val;
		}
		if($val['level'] == 3){
			$crr[$val['parent_id']][] = $val;
		}
		if($val['level'] == 1){
			$tree[] = $val;
		}
	}

	foreach ($arr as $k=>$v){
		foreach ($v as $kk=>$vv){
			$arr[$k][$kk]['sub_menu'] = empty($crr[$vv['id']]) ? array() : $crr[$vv['id']];
		}
	}
	
	foreach ($tree as $val){
		$val['tmenu'] = empty($arr[$val['id']]) ? array() : $arr[$val['id']];
		$result[$val['id']] = $val;
	}
	return $result;
}

	/**
	 * 发送店铺管理员发送通知短信
	 */
	function sendSms_notice($store_id,$order_id) {
		
		vendor('Aliyundysms.SignatureHelper');
		//require_once THINK_PATH."Library/Vendor/Aliyundysms/SignatureHelper.php";

		//use Aliyun\DySDKLite\SignatureHelper;
	    //获取阿里大鱼的配置信息
	    $config = M('config')->where(array('inc_type'=>'sms'))->select();
	    $cof = array();
	    foreach($config as $k=>$v) {
	    	$cof["$v[name]"] = $v['value'];
	    }

	    $params = array ();
	    $phone = M('store')->where(array('store_id'=>$store_id))->getField('store_phone');
	    // *** 需用户填写部分 ***

	    // fixme 必填: 请参阅 https://ak-console.aliyun.com/ 取得您的AK信息
	    $accessKeyId = $cof['sms_appkey'];
	    $accessKeySecret = $cof['sms_secretKey'];

	    // fixme 必填: 短信接收号码
	    $params["PhoneNumbers"] = $phone;

	    // fixme 必填: 短信签名，应严格按"签名名称"填写，请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/sign
	    $params["SignName"] = $cof['sms_product'];

	    // fixme 必填: 短信模板Code，应严格按"模板CODE"填写, 请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/template
	    $params["TemplateCode"] = $cof['sms_templateCode_pay'];

	    // fixme 可选: 设置模板参数, 假如模板中存在变量需要替换则为必填项
	    $order = M('order')->where(array('order_id'=>$order_id))->find();
    	$params['TemplateParam'] = Array (
                "status" => '已支付',
				"remark" => $order['order_sn']
    	);
	    // fixme 可选: 设置发送短信流水号
	    //$params['OutId'] = "12345";

	    // fixme 可选: 上行短信扩展码, 扩展码字段控制在7位或以下，无特殊需求用户请忽略此字段
	    //$params['SmsUpExtendCode'] = "1234567";


	    // *** 需用户填写部分结束, 以下代码若无必要无需更改 ***
	    if(!empty($params["TemplateParam"]) && is_array($params["TemplateParam"])) {
	        $params["TemplateParam"] = json_encode($params["TemplateParam"], JSON_UNESCAPED_UNICODE);
	    }

	    // 初始化SignatureHelper实例用于设置参数，签名以及发送请求
	    $helper = new SignatureHelper();
		
	    // 此处可能会抛出异常，注意catch
	    $content = $helper->request(
	        $accessKeyId,
	        $accessKeySecret,
	        "dysmsapi.aliyuncs.com",
	        array_merge($params, array(
	            "RegionId" => "cn-hangzhou",
	            "Action" => "SendSms",
	            "Version" => "2017-05-25",
	        ))
	        // fixme 选填: 启用https
	        // ,true
	    );

	    //echo json_encode($content);	
	}
	
	
	/**
	 * 发送审核店铺成功状态通知
	 * $apply_id  申请入驻表的ID
	 */
	function sendSms_apply_notice($apply_id) {
		
		vendor('Aliyundysms.SignatureHelper');
		//require_once THINK_PATH."Library/Vendor/Aliyundysms/SignatureHelper.php";
	    //获取阿里大鱼的配置信息
	    $config = M('config')->where(array('inc_type'=>'sms'))->select();
	    $cof = array();
	    foreach($config as $k=>$v) {
	    	$cof["$v[name]"] = $v['value'];
	    }

	    $store_apply_info = M('store_apply')->where(array('id'=>$apply_id))->find();
		
	    $params = array ();
	    // *** 需用户填写部分 ***

	    // fixme 必填: 请参阅 https://ak-console.aliyun.com/ 取得您的AK信息
	    $accessKeyId = $cof['sms_appkey'];
	    $accessKeySecret = $cof['sms_secretKey'];

	    // fixme 必填: 短信接收号码
	    $params["PhoneNumbers"] = $store_apply_info['contacts_mobile'];

	    // fixme 必填: 短信签名，应严格按"签名名称"填写，请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/sign
	    $params["SignName"] = $cof['sms_product'];

	    // fixme 必填: 短信模板Code，应严格按"模板CODE"填写, 请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/template
		if($store_apply_info['apply_state']==1){
			
			$params["TemplateCode"] = $cof['sms_apply_success'];
			
		}else if($store_apply_info['apply_state']==2){
			
			$params["TemplateCode"] = $cof['sms__apply_fail'];
		}else{
			$params["TemplateCode"] = $cof['sms_apply_success'];
			//return;
		}

	    // fixme 可选: 设置模板参数, 假如模板中存在变量需要替换则为必填项
    	$params['TemplateParam'] = Array (
                "supplier_name" => $store_apply_info['store_name'],
				"review_msg"    =>$store_apply_info['review_msg']
    	);
	    // fixme 可选: 设置发送短信流水号
	    //$params['OutId'] = "12345";

	    // fixme 可选: 上行短信扩展码, 扩展码字段控制在7位或以下，无特殊需求用户请忽略此字段
	    //$params['SmsUpExtendCode'] = "1234567";


	    // *** 需用户填写部分结束, 以下代码若无必要无需更改 ***
	    if(!empty($params["TemplateParam"]) && is_array($params["TemplateParam"])) {
	        $params["TemplateParam"] = json_encode($params["TemplateParam"], JSON_UNESCAPED_UNICODE);
	    }

	    // 初始化SignatureHelper实例用于设置参数，签名以及发送请求
	    $helper = new SignatureHelper();
		
	    // 此处可能会抛出异常，注意catch
	    $content = $helper->request(
	        $accessKeyId,
	        $accessKeySecret,
	        "dysmsapi.aliyuncs.com",
	        array_merge($params, array(
	            "RegionId" => "cn-hangzhou",
	            "Action" => "SendSms",
	            "Version" => "2017-05-25",
	        ))
	        // fixme 选填: 启用https
	        // ,true
	    );
		
/* 		var_dump($content);
		exit; */
	    //echo json_encode($content);	
	}	

function geshi($data) {
	//return floor($price*1000)/1000;
	return bcadd(0,$data,3);
}  

function sanwei($data){
	return bcadd(0,$data,3);
} 
function sanweis($data){
	return bcadd(0,$data,3);
}
function daojishi($second)
{
   $day = floor($second/(3600*24));
   $second = $second%(3600*24);//除去整天之后剩余的时间
   $newday = ($day>0) ? floor((float)$day*24) : (float)$day;
   $hour = floor((float)$second/3600);
   $second = $second%3600;//除去整小时之后剩余的时间 2021-10-13 00:00:00，恢复原价Y-m-d H:i:s
   $minute = floor($second/60);
   //返回字符串
   return '0000-'.$newday+$hour.'-'.$minute.'分';
}

function yj_price($goods_id,$price,$fenbu_id=0)
{
	$goods_yijia=M('goods')->where('goods_id='.$goods_id)->getField('yijia_quyu');
	$yijia=0;
	$goods_yijia=\json_decode($goods_yijia,true);
	if(!empty($goods_yijia)){
		foreach($goods_yijia as $qq){
		if($qq['id']==$fenbu_id){
			$yijia=$price*$qq['hl'];
			break;
		}
	}
	}
   return sanwei($yijia);
}
function yj_h1($goods_id,$price,$fenbu_id=0)
{
	$goods_yijia=M('goods')->where('goods_id='.$goods_id)->getField('yijia_quyu');
	$yijia=0;
	$goods_yijia=\json_decode($goods_yijia,true);
	if(!empty($goods_yijia)){
		foreach($goods_yijia as $qq){
		if($qq['id']==$fenbu_id){
			$yijia=$qq['hl'];
			break;
		}
	}
	}
   return sanwei($yijia);
}

/**
 * 首页接口使用的
 */
function yj_price_index_home($goods_yijia,$price,$fenbu_id=0)
{
    //$goods_yijia=M('goods')->where('goods_id='.$goods_id)->getField('yijia_quyu');
    $yijia=0;
    $goods_yijia=\json_decode($goods_yijia,true);
    if(!empty($goods_yijia)){
        foreach($goods_yijia as $qq){
            if($qq['id']==$fenbu_id){
                $yijia=$price*$qq['hl'];
                break;
            }
        }
    }
    return sanwei($yijia);
}
/**
 * 首页接口使用的
 */
function yj_price_index_home_h1($goods_yijia,$price,$fenbu_id=0)
{
    //$goods_yijia=M('goods')->where('goods_id='.$goods_id)->getField('yijia_quyu');
    $yijia=0;
    $goods_yijia=\json_decode($goods_yijia,true);
    if(!empty($goods_yijia)){
        foreach($goods_yijia as $qq){
            if($qq['id']==$fenbu_id){
                $yijia=$qq['hl'];
                break;
            }
        }
    }
    return $yijia;
}

/**
 * 获取规格图
 */
function get_spec_img($goods_spec,$img)
{
    $goods_spec = explode('_',$goods_spec);

    $imgs = '';
    foreach ($goods_spec as $item){
        $imgs = M('spec_image')->where(['spec_image_id'=>$item])->getField('src');
        if($imgs){
            break;
        }
    }

    if(!$imgs){
        return $img;
    }else{
        return $imgs;
    }
}

function update_panel_data(){
    
    // $begin = strtotime(date('Y-m-d',strtotime('-1 days',time())).' 00:00:00');
    // $end = strtotime(date('Y-m-d',time()).' 00:00:00');
    $begin = strtotime(date('Y-m-d',time()).' 00:00:00');
    $end = strtotime(date('Y-m-d',strtotime('+1 days',time())).' 00:00:00');
    $condition['add_time'] = array('between',"$begin,$end");
    $condition['order_status'] = array('in',[0,1,2]);
    
    $fenbu = M('fenbu')->field('fenbu_id')->select();
    $fenbu_id = array_column($fenbu,'fenbu_id');
    $condition['ufenbu_id'] = array('in',$fenbu_id);
    // $condition['pay_code'] = 'cod';
    //图表1 明细数据
    $order_count = M('order')->where($condition)->count();
    $order_price_count = M('order')->where($condition)->sum('order_amount');
    // dump($order_price_count);
    $order_user_count_arr = M('order')->field('count(user_id),user_id')->where($condition)->group('user_id')->select();
    $order_user_count = count($order_user_count_arr);

    $tuihuo_where = [
        'tuihuo_time'=>array('between',"$begin,$end")
    ];
    $tuihuo_amount_list = M('return_goods a')->field('SUM(((a.member_goods_price+a.yijia)*a.goods_num)) as sum')
    // ->join('ty_order b on b.order_id=a.order_id')
    ->where($tuihuo_where)
    ->group('a.return_order_sn')->select();
    // dump($tuihuo_amount_list);
    
    $tuihuo_amount = array_sum(array_column($tuihuo_amount_list,'sum'));
    // dump($tuihuo_amount);
    //图表2 线路排名
    $condition_xian['chuku_last_time'] = array('between',"$begin,$end");
    $condition_xian['order_status'] = array('in',[0,1,2,4]);
    $xian_order_list = M('order a')
    ->field('b.biaoshi_xian,sum(a.order_amount+a.yijia_heji) as order_price_count,count(a.user_id) as user_count')
    ->join('ty_users b on b.user_id=a.user_id')
    ->where($condition_xian)
    ->group('b.biaoshi_xian')->order('order_price_count desc')->limit('0,5')->select();
    
    //图表3 店铺排名
    $store_order_list = M('order a')
    ->field('b.store_name,sum(a.order_amount) as order_price_count,count(a.order_id) as order_count')
    ->join('ty_store b on b.store_id=a.store_id')
    ->where($condition)
    ->group('b.store_id')->order('order_price_count desc')->limit('0,30')->select();

    //图标4 活动产品销量
    
    $goods_order_list = M('order a')
    ->field('c.goods_name,sum(a.order_amount) as order_price_count,count(a.order_id) as order_count')
    ->join('ty_order_goods b on b.order_id=a.order_id')
    ->join('ty_goods c on c.goods_id=b.goods_id')
    ->where($condition)
    ->where(['c.prom_id'=>['neq',0]])
    ->group('b.goods_id')->order('order_price_count desc')->limit('0,5')->select();

    $start_time = strtotime(date('Y-m-d',strtotime('-4 days', time()))." 00:00:00");
    $sales_list_where = [
        'add_time'=>['egt',$start_time],
        // 'pay_code'=>'cod'
        'order_status'=>array('in',[0,1,2]),
        'ufenbu_id' => array('in',$fenbu_id)
    ];
    $sales_list = M('order')->field('DATE(FROM_UNIXTIME(add_time)) as sales_date,sum(order_amount) as sales_amount')
    ->where($sales_list_where)->group('sales_date')->select();

    $user_total = M('users')->count();
    $new_user_total = M('users')->where(['total_amount'=>['gt',0]])->count();

    
    $coupon_list_where = [
        'add_time'=>['egt',$start_time],
        'coupon_price'=>['gt',0]
    ];
    $coupon_order_list = M('order')->field('DATE(FROM_UNIXTIME(add_time)) as sales_date,sum(order_amount) as sales_amount')
    ->where($coupon_list_where)->group('sales_date')->select();

    $store_prom_where = [
        'a.add_time'=>['egt',$start_time],
        'b.prom_msg'=>'全店打折'
    ];
    $store_prom_list = M('order a')->field('DATE(FROM_UNIXTIME(a.add_time)) as sales_date,sum(a.order_amount) as sales_amount')
    ->join('ty_order_goods b on b.order_id=a.order_id')
    ->where($store_prom_where)->group('sales_date')->select();

    $goods_prom_where = [
        'a.add_time'=>['egt',$start_time],
        'b.prom_msg'=>['neq','全店打折'],
        'b.prom_id'=>['gt','0'],
    ];
    $goods_prom_list = M('order a')->field('DATE(FROM_UNIXTIME(a.add_time)) as sales_date,sum(a.order_amount) as sales_amount')
    ->join('ty_order_goods b on b.order_id=a.order_id')
    ->where($goods_prom_where)->group('sales_date')->select();
    
    // dump($goods_prom_list);

    $panel_data = [
        'order_data'=>[
            sanwei($order_count),
            sanwei($order_user_count),
            sanwei($order_price_count),
            sanwei($order_price_count/$order_user_count)
        ],
        'tuihuo_amount'=>sanwei($tuihuo_amount),
        'xian_order_list'=>$xian_order_list,
        'store_order_list'=>$store_order_list,
        'goods_order_list'=>$goods_order_list,
        'sales_list'=>[
            'sales_date'=>array_column($sales_list,'sales_date'),
            'sales_amount'=>array_column($sales_list,'sales_amount')
        ],
        'user_total'=>$user_total,
        'new_user_total'=>$new_user_total,
        'coupon_order_list'=>array_column($coupon_order_list,'sales_amount'),
        'store_prom_list'=>array_column($store_prom_list,'sales_amount'),
        'goods_prom_list'=>array_column($goods_prom_list,'sales_amount'),
    ];
    F('gd_panel_data',$panel_data);
    return $panel_data;
}

function gx_update_panel_data(){
    
    $model = new Model();
    $csj_db = $model->db('2',"mysql://tlcgp:AWzrhCa8fJ@139.9.50.10:3306/csj_shop");
    
    // $begin = strtotime(date('Y-m-d',strtotime('-1 days',time())).' 00:00:00');
    // $end = strtotime(date('Y-m-d',time()).' 00:00:00');
    $begin = strtotime(date('Y-m-d',time()).' 00:00:00');
    $end = strtotime(date('Y-m-d',strtotime('+1 days',time())).' 00:00:00');
    $condition['add_time'] = array('between',"$begin,$end");
    $condition['order_status'] = array('in',[0,1,2]);
    
    $fenbu = $csj_db->table('ty_fenbu')->field('fenbu_id')->select();
    $fenbu_id = array_column($fenbu,'fenbu_id');
    $condition['ufenbu_id'] = array('in',$fenbu_id);
    // $condition['pay_code'] = 'cod';
    //图表1 明细数据
    $order_count = $csj_db->table('ty_order')->where($condition)->count();
    $order_price_count = $csj_db->table('ty_order')->where($condition)->sum('order_amount');
    $order_user_count_arr = $csj_db->table('ty_order')->field('count(user_id),user_id')->where($condition)->group('user_id')->select();
    $order_user_count = count($order_user_count_arr);
    // dump($order_price_count);

    $tuihuo_where = [
        'tuihuo_time'=>array('between',"$begin,$end")
    ];
    $tuihuo_amount_list = $csj_db->table('ty_return_goods a')->field('SUM(((a.member_goods_price+a.yijia)*a.goods_num)) as sum')
    // ->join('ty_order b on b.order_id=a.order_id')
    ->where($tuihuo_where)
    ->group('a.return_order_sn')->select();
    
    $tuihuo_amount = array_sum(array_column($tuihuo_amount_list,'sum'));

    //图表2 线路排名
    $condition_xian['chuku_last_time'] = array('between',"$begin,$end");
    $condition_xian['order_status'] = array('in',[0,1,2,4]);
    $xian_order_list = $csj_db->table('ty_order a')
    ->field('b.biaoshi_xian,sum(a.order_amount+a.yijia_heji) as order_price_count,count(a.user_id) as user_count')
    ->join('ty_users b on b.user_id=a.user_id')
    ->where($condition_xian)
    ->group('b.biaoshi_xian')->order('order_price_count desc')->limit('0,5')->select();
    
    //图表3 店铺排名
    $store_order_list = $csj_db->table('ty_order a')
    ->field('b.store_name,sum(a.order_amount) as order_price_count,count(a.order_id) as order_count')
    ->join('ty_store b on b.store_id=a.store_id')
    ->where($condition)
    ->group('b.store_id')->order('order_price_count desc')->limit('0,30')->select();

    //图标4 活动产品销量
    
    $goods_order_list = $csj_db->table('ty_order a')
    ->field('c.goods_name,sum(a.order_amount) as order_price_count,count(a.order_id) as order_count')
    ->join('ty_order_goods b on b.order_id=a.order_id')
    ->join('ty_goods c on c.goods_id=b.goods_id')
    ->where($condition)
    ->where(['c.prom_id'=>['neq',0]])
    ->group('b.goods_id')->order('order_price_count desc')->limit('0,5')->select();

    $start_time = strtotime(date('Y-m-d',strtotime('-4 days', time()))." 00:00:00");
    $sales_list_where = [
        'add_time'=>['egt',$start_time],
        // 'pay_code'=>'cod'
        'order_status'=>array('in',[0,1,2]),
        'ufenbu_id' => array('in',$fenbu_id)
    ];
    $sales_list = $csj_db->table('ty_order')->field('DATE(FROM_UNIXTIME(add_time)) as sales_date,sum(order_amount) as sales_amount')
    ->where($sales_list_where)->group('sales_date')->select();

    $user_total = $csj_db->table('ty_users')->count();
    $new_user_total = $csj_db->table('ty_users')->where(['total_amount'=>['gt',0]])->count();

    $panel_data = [
        'order_data'=>[
            sanwei($order_count),
            sanwei($order_user_count),
            sanwei($order_price_count),
            sanwei($order_price_count/$order_user_count)
        ],
        'tuihuo_amount'=>sanwei($tuihuo_amount),
        'xian_order_list'=>$xian_order_list,
        'store_order_list'=>$store_order_list,
        'goods_order_list'=>$goods_order_list,
        'sales_list'=>[
            'sales_date'=>array_column($sales_list,'sales_date'),
            'sales_amount'=>array_column($sales_list,'sales_amount')
        ],
        'user_total'=>$user_total,
        'new_user_total'=>$new_user_total
    ];
    F('gx_panel_data',$panel_data);
    return $panel_data;
}


/**
 * 检测店铺和用户浮点有没有特定
 * */
function check_float($store_id,$user_id,$goods_id=0){
    $store = M('store_floating')->where(['store_id'=>$store_id,'user_id'=>$user_id])->find();
    //先查看是否存在goods_id的浮价，如何存在就返回，不存在就检测品牌
    if(!empty($store)){
        $goods_status = 0;
        if(!empty($store['goods_ids'])){
            $store['goods_ids'] = json_decode($store['goods_ids'],true);
            foreach ($store['goods_ids'] as $k=>$v){
                if($goods_id == $v['goods_id']){
                    $goods_status = 1;
                    $store['floating'] = $v['floating'];
                    break;
                    //停止循环
                }
            }
        }
        if($goods_status == 0){
            //检测品牌是否存在
            if(!empty($store['brand_id'])){
                $store['brand_id'] = json_decode($store['brand_id'],true);
                //获取商品的品牌
                $goods_brand = M('goods')->where(['goods_id'=>$goods_id])->getField('brand_id');
                foreach ($store['brand_id'] as $k=>$v){
                    $brand = M('brand')->where(['id'=>$v['brand_id']])->getField('name');
                    $brand_list = M('brand')->where(['name'=>$brand])->getField('id',true);
                    if(in_array($goods_brand,$brand_list)){
                        $store['floating'] = $v['floating'];
                        break;
                    }
                }
            }
        }
        $float = $store['floating'];
    }else{
        return 0;
    }
    return $float;
}